#!/usr/bin/python2.5
#
# Copyright (C) 2008 Tom Brown
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Static KML Viewer for Google App Engine.

This handler loads a KML file and displays the last 3 points using the maps
static image API. It makes KML readable on machines with primative browsers,
such as Pocket IE.
"""

from google.appengine.api import urlfetch
from google.appengine.ext import webapp
import logging
import random
import re
import time
import urllib
import urlparse
import wsgiref.handlers
from xml.etree import ElementTree as ET

KEY = "ABQIAAAAFO8mbS0YfqCCryVHWGMAYhT62wAJBQq2MisMEK-hkANTr3GioRQ3Cu2s7GbLk_eepNmLeOkMhwxgzQ"
APPSPOT_KEY = "ABQIAAAAFO8mbS0YfqCCryVHWGMAYhRlJ9RzUDXpH9_g5MUmyDtDKslHQhRll2JMUNoHGqwGHHTSCgXDFRuSTw"

class ResponseFinished(Exception):
  pass

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write("KML viewer that works everywhere<br>")
    self.response.headers['Content-Type'] = 'text/html'
    try:
      param = self.GetCleanParamDict()
      root = ET.fromstring(self.FetchKml(param))
      locations = self.LastNPlacemarks(root)
    except ResponseFinished, e:
      return
    self.response.out.write("<img src='%s'>" % (self.GetImageUrl(param, locations)))
    self.response.out.write(" <br>")

    def SelfLink(text, param_ref, modify_param, modify_lambda):
      """Return an <a> tag with modify_param modified by modify_lambda."""
      param = dict(param_ref)
      param[modify_param] = modify_lambda(param[modify_param])
      return "<a href='/?%s'>%s</a>" % (urllib.urlencode(param), text)

    self.response.out.write("Zoom: ")
    if param["zoom"] < 17:
      self.response.out.write(" %s" % SelfLink("+", param, "zoom", lambda z: z + 1))
    else:
      self.response.out.write(" +")
    if param["zoom"] > 1:
      self.response.out.write(" %s" % SelfLink("-", param, "zoom", lambda z: z - 1))
    else:
      self.response.out.write(" -")
    self.response.out.write(" <br>")
    self.response.out.write("Size: ")
    if param["size"] < 600:
      self.response.out.write(" %s" % SelfLink("+", param, "size", lambda s: s + 100))
    else:
      self.response.out.write(" +")
    if param["size"] > 100:
      self.response.out.write(" %s" % SelfLink("-", param, "size", lambda s: s - 100))
    else:
      self.response.out.write(" -")
    self.response.out.write("<table><tr>")
    for (lng, lat, desc), color in zip(locations, ["", "_yellow", "_white"]):
      self.response.out.write("<td>")
      self.response.out.write("<img src='http://maps.google.com/intl/en_us/mapfiles/marker%s.png'>" % color)
      self.response.out.write(desc)
      self.response.out.write("</td>")
    self.response.out.write("</tr><table>")

  def GetCleanParamDict(self):
    """Get request parameters as a dict {name: int}."""
    param = {}
    zoom = self.request.get("zoom")
    if re.match(r"^\d{1,2}$", zoom):
      param["zoom"] = int(zoom)
    else:
      param["zoom"] = 10

    size = self.request.get("size")
    if re.match(r"^\d{2,3}$", size):
      param["size"] = int(size)
    else:
      param["size"] = 300

    url_param = self.request.get("url")
    url_parsed = urlparse.urlparse(url_param)
    if url_parsed.scheme == "http" and url_parsed.netloc and url_parsed.path:
      param["url"] = url_param
    else:
      self.response.out.write("""
      <form action=/ method=get>URL: <input name=url><input type=submit></form>
      """)
      raise ResponseFinished()


    return param


  def GetImageUrl(self, request_param, locations):
    """Return the URL of a static map image."""
    marker_list = []
    for (lng, lat, desc), color in zip(locations, ["red", "yellow", "white"]):
      marker_list.append("%s,%s,%s" % (lat, lng, color))
    latest_markers = "|".join(marker_list)

    param = dict(request_param)
    param["markers"] = "|".join(marker_list)
    param["size"] = "%(size)dx%(size)d" % request_param
    if self.request.host.find("appspot") != -1:
      param["key"] = APPSPOT_KEY
    else:
      param["key"] = KEY
    # TODO: Pick better default. Can't let /staticmap pick it because I would be
    # sure what to use in URL for + and - zoom
    param["zoom"] = request_param["zoom"]
    if request_param["size"] <= 200:
      param["maptype"] = "mobile"
    return "http://maps.google.com/staticmap?%s" % urllib.urlencode(param)


  def LastNPlacemarks(self, root, n=3):
    """Return [((lat,lng,html),...] where lat lng and html are strings."""
    points = []
    for placemark in root.getiterator("{http://earth.google.com/kml/2.0}Placemark"):
      if placemark.find("{http://earth.google.com/kml/2.0}Point"):
        points.append(placemark)
    placemarks = points[-n:]
    def ExtractLatLngHtml(placemark):
      point = placemark.find("{http://earth.google.com/kml/2.0}Point")
      if point:
        coordinates = point.find("{http://earth.google.com/kml/2.0}coordinates")
        m = re.match(r"([+-]?\d+\.\d+),([+-]?\d+\.\d+)(,\d+)?", coordinates.text)
        return m.group(1), m.group(2), placemark.find("{http://earth.google.com/kml/2.0}description").text

    return [ExtractLatLngHtml(p) for p in placemarks]
    

  def FetchKml(self, request_param):
    # return open("thecapcom.kml").read()
    #url = "http://luisespinosa.com/trackme/routes/thecapcom.kml?=%d" % (random.randint(1,100000))
    url = request_param["url"]
    if not url:
      logging.info("no url provided")
      return None
    start_time = time.clock()
    result = urlfetch.fetch(url)
    logging.info("fetch of '%s' at %s" % (url, start_time))
    logging.info("fetch of '%s' returned status %d in %dus" %
                  (url, result.status_code, int((time.clock() - start_time) * 1000000)))
    if result.status_code == 200:
      return result.content
    else:
      raise Exception("Fetch returned code %s" % result.status_code)


def main():
  application = webapp.WSGIApplication([('/', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
